package interceptor.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author quan
 * @Description 定义一个拦截器
 * @Date 2023/7/28 17:19
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否登录：如果session为空，不去创建
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute("username")!=null){
            //说明是登录状态，不进行拦截
            return true;
        }
        //否则说明不是登录状态，直接返回：给出提示：没有权限登录
        response.setStatus(401);
        return false;
    }
}
